package cn.aishua.util;

import cn.aishua.network.DownloadPicTask;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ImageView;

public class ImageLoader
{

    private static ImageLoader instance;

    private MemoryCache mCache;
    private FileCache fCache;
    private Context context;

    private ImageLoader()
    {
    }

    public synchronized static ImageLoader getInstance( Context context )
    {
        if( instance == null )
        {
            instance = new ImageLoader();
            instance.mCache = MemoryCache.getInstance();
            instance.fCache = new FileCache( context );
            instance.context = context;
        }
        return instance;
    }

    public void loadImage( String url, final ImageView imageView )
    {
        Bitmap bitmap = null;
        final String key = url.substring( url.lastIndexOf( "/" ) + 1 );
        Log.d( "ImageLoader", "key: " + key );
        Log.d( "ImageLoader", "get image from memory cache..." );
        if( ( bitmap = mCache.getBitmap( key ) ) == null )
        {
            Log.d( "ImageLoader", "get image from file cache..." );
            if( ( bitmap = fCache.getBitmap( key ) ) == null )
            {
                boolean downloadPicUnder2G3G = context.getSharedPreferences( "setting", Context.MODE_PRIVATE )
                    .getBoolean( SharedPrefConst.SHARED_PREF_BOOL_DONW_PIC_UNDER_2G3G, false );

                if( downloadPicUnder2G3G || NetworkState.isWifiAvailable( context ) )
                {
                    Log.d( "ImageLoader", "get image from server" );
                    new DownloadPicTask( new CallBack()
                    {

                        @Override
                        public void onFinished( Bitmap bitmap )
                        {
                            mCache.putBitmap( key, bitmap );
                            fCache.putBitmap( key, bitmap );
                            imageView.setImageBitmap( mCache.getBitmap( key ) );
                        }
                    } ).execute( url );
                    //                    return mCache.getBitmap( key );
                }
            }
        }
        if( bitmap != null )
        {
            imageView.setImageBitmap( bitmap );
        }
        //        return bitmap;
    }

    public interface CallBack
    {
        public void onFinished( Bitmap bitmap );
    }

}
